/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sv.com.intesal.reporte.controlador;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRXmlDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.commons.collections.map.HashedMap;
import sv.com.intesal.conexion.cConexion;
import sv.com.intesal.reporte.bean.Reporte;

/**
 *
 * @author andrew_jerez
 */
@ManagedBean(name = "GenerarReporte")
public class GenerarReporte implements Serializable {

    public GenerarReporte() {
    }
    private String nombreDocumento = "";
    private String formatoReporte = "";
    private String directorioReporte = "";
    /*Copia FUNCIONAL */

    public void generarReporte(Reporte r) throws Exception {

        try {
            Connection conn = cConexion.conectar();
            if (r.getMap_r() == null) {
                r.setMap_r(this.generarMap(r));
            }
            TipoReporteControlador tr = new TipoReporteControlador();
            r.setTipoReporte(tr.getTipoRepote(r.getTipoReporte().getExtension_tr()));



            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            String path = context.getExternalContext().getRealPath(r.getDirectorio_r());

            File reportFile = new File(path);
            byte bytes[] = JasperRunManager.runReportToPdf(reportFile.getPath(), r.getMap_r(), conn);

            response.setContentType(r.getTipoReporte().getContextType());
            response.setHeader(r.getTipoReporte().getHeaderName(), r.getTipoReporte().getHeaderValue() + r.getNombre_r() + r.getTipoReporte().getExtension_tr());

            response.setContentLength(bytes.length);
            ServletOutputStream ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);
            ouputStream.flush();
            ouputStream.close();
            context.responseComplete();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    private Map generarMap(Reporte r) throws Exception {
        Map map = new HashedMap();
        try {
            map.put("CompleteQuery", r.getSql_r());
            return map;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public void generateReport(Map reportParams,Reporte r) throws ClassNotFoundException, SQLException, IOException, JRException {

        try {
            Connection conn = cConexion.conectar();

            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

            System.out.println("real path =" + context.getExternalContext().getRealPath(r.getDirectorio_r()));
            String path = context.getExternalContext().getRealPath(r.getDirectorio_r());

            File reportFile = new File(path);




            System.out.println("imprimir = " + r.getTipoReporte().getExtension_tr());

            if (r.getTipoReporte().getExtension_tr().equals("pdf")) {

                byte bytes[] = JasperRunManager.runReportToPdf(reportFile.getPath(), reportParams, conn);
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "attachment; filename=" + r.getNombre_r() + "."+ r.getTipoReporte().getExtension_tr());
                response.setContentLength(bytes.length);
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(bytes, 0, bytes.length);
                ouputStream.flush();
                ouputStream.close();



            } else if (r.getTipoReporte().getExtension_tr().equals("xlsx")) {

                JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportParams, conn);

                JRXlsExporter exporter = new JRXlsExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
                exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
                exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
                exporter.exportReport();


                response.setHeader("Content-Disposition", "attachment; filename=Report.xlsx");
                response.setContentType("application/vnd.ms-excel");
                context.responseComplete();





            } else if (r.getTipoReporte().getExtension_tr().equals("xls")) {
                response.setHeader("Content-Disposition", "attachment; filename=Report.xls");
                response.setContentType("application/vnd.ms-excel");

            } else if (r.getTipoReporte().getExtension_tr().equals("txt")) {
                response.setHeader("Content-Disposition", "attachment; filename=Report.txt");
                response.setContentType("text/plain");

            } else if (r.getTipoReporte().getExtension_tr().equals("doc")) {
                response.setHeader("Content-Disposition", "attachment; filename=Report.doc");
                response.setContentType("application/msword");

            } else if (r.getTipoReporte().getExtension_tr().equals("docx")) {
                response.setHeader("Content-Disposition", "attachment; filename=Report.docx");
                response.setContentType("application/msword");

            } else if (r.getTipoReporte().getExtension_tr().equals("csv")) {
                response.setHeader("Content-Disposition", "attachment; filename=Report.csv");
                response.setContentType("application/csv");

            } else {
                System.out.println("default");
            }


            context.responseComplete();

        } catch (Exception e) {
            System.out.println("catch error");
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }

        /*
         * JRXmlDataSource xmlDataSource = new JRXmlDataSource(
         */
        /*
        public void generateReport(Map reportParams, String strDirectorioReporte, String xmlDataSourceString) throws ClassNotFoundException, SQLException, IOException, JRException {

        try {
        Connection conn = cConexion.conectar();

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

        System.out.println("real path =" + context.getExternalContext().getRealPath(strDirectorioReporte));
        String path = context.getExternalContext().getRealPath(strDirectorioReporte);

        File reportFile = new File(path);
        //            File xmlFile = new File(xmlDataSourceString);

        System.out.println("before parse");
        JRXmlDataSource xmlDataSource = new JRXmlDataSource(xmlDataSourceString, "/Reporte/REGISTRO");
        //            JRXmlDataSource xmlDataSource = new JRXmlDataSource(xmlFile, "/Reporte/REGISTRO");
        System.out.println("before bytes");
        byte bytes[] = JasperRunManager.runReportToPdf(reportFile.getPath(), reportParams, xmlDataSource);



        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(bytes, 0, bytes.length);
        ouputStream.flush();
        ouputStream.close();

        context.responseComplete();
        } catch (Exception e) {
        System.out.println("catch error");
        e.printStackTrace();
        } finally {
        System.out.println("finally");
        }

         */
    }

    public String getFormatoReporte() {
        return formatoReporte;
    }

    public void setFormatoReporte(String formatoReporte) {
        this.formatoReporte = formatoReporte;
    }

    public String getNombreDocumento() {
        return nombreDocumento;
    }

    public void setNombreDocumento(String nombreDocumento) {
        this.nombreDocumento = nombreDocumento;
    }

    public String getDirectorioReporte() {
        return directorioReporte;
    }

    public void setDirectorioReporte(String directorioReporte) {
        this.directorioReporte = directorioReporte;
    }
}
